<template>
  <div class="modbus-model-container">
    <a-space direction="vertical" style="width: 100%">
      <a-space>
        <a-button type="primary" @click="handleAdd">新建</a-button>
        <a-button @click="handleRefresh">刷新</a-button>
      </a-space>

      <a-table :columns="columns" :data-source="dataSource" :rowKey="(record) => record.id">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'operation'">
            <a-space>
              <a @click="handleEdit(record)">编辑</a>
              <a @click="handleDelete(record)">删除</a>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-space>

    <!-- 添加/编辑模态框 -->
    <a-modal v-model:open="modalVisible" :title="modalTitle" width="800px" @ok="handleModalOk" @cancel="handleModalCancel">
      <a-form ref="formRef" :model="formState" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="模型名称" name="modelName" :rules="[{ required: true, message: '请输入模型名称' }]">
          <a-input v-model:value="formState.modelName" />
        </a-form-item>

        <a-form-item label="模型描述" name="modelDesc">
          <a-input v-model:value="formState.modelDesc" />
        </a-form-item>

        <a-form-item label="组态模型" name="configModel">
          <a-input v-model:value="formState.configModel" />
        </a-form-item>

        <a-form-item label="组态展示页面" name="configPage">
          <a-input v-model:value="formState.configPage" />
        </a-form-item>

        <a-form-item label="连接方式" name="connectionType" :rules="[{ required: true, message: '请选择连接方式' }]">
          <a-select v-model:value="formState.connectionType" @change="handleConnectionTypeChange">
            <a-select-option value="serial">串口</a-select-option>
            <a-select-option value="tcpClient">TCP/IP客户端</a-select-option>
            <a-select-option value="tcpServer">TCP/IP服务端</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="超时时间(毫秒)" name="timeout" :rules="[{ required: true, message: '请输入超时时间' }]">
          <a-input-number v-model:value="formState.timeout" :min="100" :max="10000" />
        </a-form-item>

        <a-form-item label="数据格式" name="dataFormat" :rules="[{ required: true, message: '请选择数据格式' }]">
          <a-select v-model:value="formState.dataFormat">
            <a-select-option value="bigEndian">大端</a-select-option>
            <a-select-option value="littleEndian">小端</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="模式" name="mode" :rules="[{ required: true, message: '请选择模式' }]">
          <a-select v-model:value="formState.mode">
            <a-select-option value="RTU">RTU</a-select-option>
            <a-select-option value="ASCII">ASCII</a-select-option>
          </a-select>
        </a-form-item>

        <!-- 串口相关配置 -->
        <template v-if="formState.connectionType === 'serial'">
          <a-form-item label="串口" name="serialPort" :rules="[{ required: true, message: '请输入串口' }]">
            <a-input v-model:value="formState.serialPort" />
          </a-form-item>

          <a-form-item label="串口波特率" name="baudRate" :rules="[{ required: true, message: '请选择波特率' }]">
            <a-select v-model:value="formState.baudRate">
              <a-select-option v-for="rate in baudRates" :key="rate" :value="rate">
                {{ rate }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item label="数据位" name="dataBits" :rules="[{ required: true, message: '请选择数据位' }]">
            <a-select v-model:value="formState.dataBits">
              <a-select-option v-for="bits in [6, 7, 8]" :key="bits" :value="bits">
                {{ bits }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item label="校验位" name="parity" :rules="[{ required: true, message: '请选择校验位' }]">
            <a-select v-model:value="formState.parity">
              <a-select-option value="None">None</a-select-option>
              <a-select-option value="Even">Even</a-select-option>
              <a-select-option value="Odd">Odd</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item label="停止位" name="stopBits" :rules="[{ required: true, message: '请选择停止位' }]">
            <a-select v-model:value="formState.stopBits">
              <a-select-option v-for="bits in [1, 1.5, 2]" :key="bits" :value="bits">
                {{ bits }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item label="流控" name="flowControl" :rules="[{ required: true, message: '请选择流控' }]">
            <a-select v-model:value="formState.flowControl">
              <a-select-option value="None">None</a-select-option>
              <a-select-option value="XOn/XOff">XOn/XOff</a-select-option>
              <a-select-option value="RTS/CTS">RTS/CTS</a-select-option>
            </a-select>
          </a-form-item>
        </template>
      </a-form>
    </a-modal>
  </div>
</template>
  
  <script setup>
import { ref, reactive, onMounted } from 'vue';
import { Modal, message } from 'ant-design-vue';

// 表格列定义
const columns = [
  {
    title: '序号',
    dataIndex: 'id',
    key: 'id',
    width: 80,
  },
  {
    title: '模型名称',
    dataIndex: 'modelName',
    key: 'modelName',
  },
  {
    title: '模型描述',
    dataIndex: 'modelDesc',
    key: 'modelDesc',
  },
  {
    title: '连接方式',
    dataIndex: 'connectionType',
    key: 'connectionType',
    customRender: ({ text }) => {
      const map = {
        serial: '串口',
        tcpClient: 'TCP/IP客户端',
        tcpServer: 'TCP/IP服务端',
      };
      return map[text] || text;
    },
  },
  {
    title: '模式',
    dataIndex: 'mode',
    key: 'mode',
  },
  {
    title: '操作',
    key: 'operation',
    width: 150,
  },
];

// 数据源
const dataSource = ref([
  {
    id: 1,
    modelName: '每件单温度传感器',
    modelDesc: '每件单温度传感器',
    connectionType: 'tcpServer',
    mode: 'RTU',
    timeout: 1000,
    dataFormat: 'bigEndian',
    configModel: '演示应用',
    configPage: '首页',
  },
  {
    id: 2,
    modelName: '4路灯光控制模块',
    modelDesc: '4路灯光控制模块',
    connectionType: 'tcpServer',
    mode: 'RTU',
    timeout: 1000,
    dataFormat: 'bigEndian',
    configModel: '演示应用',
    configPage: '首页',
  },
]);

// 波特率选项
const baudRates = [1200, 2400, 4800, 9600, 19200, 38400, 115200];

// 模态框状态
const modalVisible = ref(false);
const modalTitle = ref('添加Modbus数据模型');
const isEdit = ref(false);
const currentId = ref(null);

// 表单状态
const formState = reactive({
  modelName: '',
  modelDesc: '',
  configModel: '',
  configPage: '',
  connectionType: 'serial',
  timeout: 1000,
  dataFormat: 'bigEndian',
  mode: 'RTU',
  // 串口相关字段
  serialPort: '',
  baudRate: 2400,
  dataBits: 8,
  parity: 'None',
  stopBits: 1,
  flowControl: 'None',
});

const formRef = ref();

// 加载数据
const loadData = () => {
  // 这里可以替换为实际的API调用
  console.log('加载数据...');
};

// 处理添加按钮
const handleAdd = () => {
  modalTitle.value = '添加Modbus数据模型';
  isEdit.value = false;
  resetForm();
  modalVisible.value = true;
};

// 处理编辑按钮
const handleEdit = (record) => {
  modalTitle.value = '编辑Modbus数据模型';
  isEdit.value = true;
  currentId.value = record.id;

  // 填充表单数据
  Object.keys(formState).forEach((key) => {
    if (record[key] !== undefined) {
      formState[key] = record[key];
    }
  });

  modalVisible.value = true;
};

// 处理删除按钮
const handleDelete = (record) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除模型 "${record.modelName}" 吗？`,
    okText: '确认',
    cancelText: '取消',
    onOk: () => {
      dataSource.value = dataSource.value.filter((item) => item.id !== record.id);
      message.success('删除成功');
    },
  });
};

// 处理刷新按钮
const handleRefresh = () => {
  loadData();
  message.success('刷新成功');
};

// 处理模态框确定
const handleModalOk = async () => {
  try {
    await formRef.value.validateFields();

    const formData = { ...formState };

    if (isEdit.value) {
      // 更新数据
      const index = dataSource.value.findIndex((item) => item.id === currentId.value);
      if (index !== -1) {
        dataSource.value[index] = { ...formData, id: currentId.value };
      }
      message.success('更新成功');
    } else {
      // 添加数据
      const newId = dataSource.value.length > 0 ? Math.max(...dataSource.value.map((item) => item.id)) + 1 : 1;
      dataSource.value.push({ ...formData, id: newId });
      message.success('添加成功');
    }

    modalVisible.value = false;
  } catch (error) {
    console.log('验证失败:', error);
  }
};

// 处理模态框取消
const handleModalCancel = () => {
  modalVisible.value = false;
};

// 重置表单
const resetForm = () => {
  Object.keys(formState).forEach((key) => {
    if (key === 'connectionType') {
      formState[key] = 'serial';
    } else if (key === 'timeout') {
      formState[key] = 1000;
    } else if (key === 'dataFormat') {
      formState[key] = 'bigEndian';
    } else if (key === 'mode') {
      formState[key] = 'RTU';
    } else if (key === 'baudRate') {
      formState[key] = 2400;
    } else if (key === 'dataBits') {
      formState[key] = 8;
    } else if (key === 'parity') {
      formState[key] = 'None';
    } else if (key === 'stopBits') {
      formState[key] = 1;
    } else if (key === 'flowControl') {
      formState[key] = 'None';
    } else {
      formState[key] = '';
    }
  });
};

// 处理连接方式变化
const handleConnectionTypeChange = (value) => {
  // 可以根据需要在这里处理连接方式变化后的逻辑
  console.log('连接方式变为:', value);
};

// 初始化加载数据
onMounted(() => {
  loadData();
});
</script>
  
  <style scoped>
.modbus-model-container {
  padding: 20px;
  background: #fff;
}
</style>